package com.ztc.ZtcTransport.service;

import com.aqgj.SysArea.dao.SysAreaDao;
import com.aqgj.User.bean.User;
import com.aqgj.User.dao.UserDao;
import com.aqgj.util.DateFarmatUtils;
import com.aqgj.util.JsonWrapper;
import com.aqgj.util.Pager;
import com.ztc.ZtcCar.bean.ZtcCar;
import com.ztc.ZtcCar.dao.ZtcCarDao;
import com.ztc.ZtcClasses.bean.ZtcClasses;
import com.ztc.ZtcClasses.dao.ZtcClassesDao;
import com.ztc.ZtcClassesForSale.bean.ZtcClassesForSale;
import com.ztc.ZtcClassesForSale.dao.ZtcClassesForSaleDao;
import com.ztc.ZtcDriver.bean.ZtcDriver;
import com.ztc.ZtcDriver.dao.ZtcDriverDao;
import com.ztc.ZtcRoute.bean.ZtcRoute;
import com.ztc.ZtcRoute.dao.ZtcRouteDao;
import com.ztc.ZtcTransportDefaultPercentage.bean.ZtcTransportDefaultPercentage;
import com.ztc.ZtcTransportDefaultPercentage.dao.ZtcTransportDefaultPercentageDao;
import com.ztc.ZtcTransportPercentageScale.bean.ZtcTransportPercentageScale;
import com.ztc.ZtcTransportPercentageScale.dao.ZtcTransportPercentageScaleDao;
import com.ztc.ZtcWallet.bean.ZtcWallet;
import com.ztc.ZtcWallet.dao.ZtcWalletDao;
import com.ztc.util.ZtcCompanyScaleUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ztc.ZtcTransport.bean.ZtcTransport;
import com.ztc.ZtcTransport.dao.ZtcTransportDao;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service("ZtcTransport")
public class ZtcTransportManager {

    private static final Logger log = LogManager.getLogger(ZtcTransportManager.class);
    @Autowired
    ZtcTransportDao ztcTransportDao;
    @Autowired
    UserDao userDao;
    @Autowired
    ZtcDriverDao ztcDriverDao;
    @Autowired
    ZtcCarDao ztcCarDao;
    @Autowired
    SysAreaDao sysAreaDao;
    @Autowired
    ZtcRouteDao ztcRouteDao;
    @Autowired
    ZtcClassesDao ztcClassesDao;
    @Autowired
    ZtcClassesForSaleDao ztcClassesForSaleDao;

    public String save(ZtcTransport ztcTransport) {
        return ztcTransportDao.save(ztcTransport);
    }

    public String update(ZtcTransport ztcTransport) {
        return ztcTransportDao.update(ztcTransport);
    }
    /**
     * 保存公司信息.
     *
     * @param ztcTransport 公司信息
     * @param type         公司类型
     * @param status       状态
     * @param parentId     父级公司id
     * @return 是否保存成功
     */
    public HashMap<String, Object> saveZtcTransport(ZtcTransport ztcTransport, Integer type, Integer status, String parentId) {
        ztcTransport.setStatus(status);
        ztcTransport.setSignTime(new Date());
        ztcTransport.setType(type);
        ztcTransport.setParentId(parentId);
        ztcTransport.setIsPermission(2);
        ZtcTransport test = ztcTransportDao.findUniqueBy("fullName", ztcTransport.getFullName());
        if (test != null) {
            return JsonWrapper.failureWrapperMsg("公司已存在，无法注册!");
        }
        String id= ztcTransportDao.save(ztcTransport);
        return JsonWrapper.successWrapper(id);
    }

    public void delZtcTransport(String zid) {
        ztcTransportDao.removeById(zid);
    }

    public ZtcTransport get(String zid) {
        return ztcTransportDao.get(zid);
    }

    public ZtcTransport findUniqueBy(String propertyName, Object value) {
        return ztcTransportDao.findUniqueBy(propertyName, value);
    }

    public List<ZtcTransport> findBy(String propertyName1, Object value1, String propertyName2, Object value2) {
        return ztcTransportDao.findBy(propertyName1, value1, propertyName2, value2);
    }

    public List<ZtcTransport> findBy(String propertyName, Object value) {
        return ztcTransportDao.findBy(propertyName, value);
    }

    /**
     * 当前公司id获取旗下所管理公司.
     * @param currZid  当前用户公司ID
     * @param pageSize  每页大小
     * @param pageNumber  页码
     * @param type     指定类型
     * @return   所有满足条件的公司信息
     */
    public HashMap<String, Object> getAllCompany(String currZid,Integer pageSize,Integer pageNumber,Integer type,String search,Integer status,Integer cType) {
        Pager<ZtcTransport> ztcTransports = ztcTransportDao.getAllCompany(currZid,pageSize,pageNumber,type,search,status,cType);
        List<HashMap<String, Object>> list = new ArrayList<>();
        HashMap<String, Object> map = null;
        if (ztcTransports.getContent().size() > 0) {
            for (ZtcTransport ztc : ztcTransports.getContent()) {
                map = new HashMap<>();
                User user=userDao.findUniqueBy("account",ztc.getSignTel());
                map.put("name", ztc.getFullName());
                map.put("signTel", ztc.getSignTel());
                map.put("address", ztc.getAddress());
                map.put("status", ztc.getStatus());
                map.put("email", ztc.getEmail());
                if (type==4){
                    map.put("manager",user==null?"":user.getAccount());
                }
                map.put("location",sysAreaDao.findUniqueBy("code",ztc.getAreaCode()).getFullName());
                map.put("type", getCompanyType(ztc.getType()));
                map.put("time", DateFarmatUtils.format(ztc.getSignTime()));
                map.put("id", ztc.getId());
                map.put("levelType", ztc.getType());
                list.add(map);
            }
            return JsonWrapper.successPagerWrapper(list,ztcTransports.getRecordTotal());
        }
        return JsonWrapper.successWrapper("");
    }

    public List<ZtcTransport> getAll() {return this.ztcTransportDao.getAll();}

    //公司类型
    private String getCompanyType(Integer type) {
        String temp = "";
        switch (type) {
            case 0: temp = "平台公司";break;
            case 1: temp = "省级公司";break;
            case 2: temp = "地级公司";break;
            case 3: temp = "运营公司";break;
            case 4: temp = "车方公司";break;
        }
        return temp;
    }

    /**
     * 审核公司(通过审核).
     *
     * @param ztcTransport 待审核公司
     * @param status       通过状态
     * @param remark       审核意见
     * @param endTime      有效期结束时间
     * @return
     */
    @Transactional
    public HashMap<String, Object> reviewedCompany(ZtcTransport ztcTransport, Integer status, String remark, String endTime,User user) {
        if(ztcTransport.getType()==3){
            ztcTransport.setEndValidateTime(DateFarmatUtils.stringToDate(endTime,DateFarmatUtils.FORMAT_SHORT));
            ztcTransport.setBeginValidateTime(new Date());
        }
        ztcTransport.setStatus(status);
        ztcTransport.setExamineRemark(remark);
        ztcTransport.setExamineUserId(user.getId());
        ztcTransport.setExamineUsername(user.getAccount());
        ztcTransport.setExamineTime(new Date());
        ztcTransportDao.save(ztcTransport);
        List<ZtcDriver> ztcDrivers = ztcDriverDao.findBy("transportId", ztcTransport.getId());
        List<ZtcCar> ztcCars=ztcCarDao.findBy("transportId", ztcTransport.getId());
        if (ztcDrivers.size() > 0) {
            for (ZtcDriver ztcDriver : ztcDrivers) {
                if("5".equals(ztcDriver.getStatus())){//注册待审核状态的司机
                    ztcDriver.setStatus("1");
                    ztcDriver.setExamineUserId(user.getId());
                    ztcDriver.setExamineTime(new Date());
                    ztcDriver.setBeginValidateTime(new Date());
                    ztcDriver.setEndValidateTime(DateFarmatUtils.stringToDate(endTime,DateFarmatUtils.FORMAT_SHORT));
                    ztcDriverDao.save(ztcDriver);
                }
            }
        }
        if (ztcCars.size() > 0) {
            for (ZtcCar ztcCar : ztcCars) {
                if(ztcCar.getStatus()==5){//注册待审核状态的车
                    ztcCar.setStatus(1);
                    ztcCar.setExamineUserId(user.getId());
                    ztcCar.setExamineTime(new Date());
                    ztcCarDao.save(ztcCar);
                }
            }
        }
        return JsonWrapper.successWrapper("审核成功!");
    }

    //获取所有省公司和地级公司
    public HashMap<String,Object> getAreaCompany(Integer pageSize, Integer pageNumber, String search) {
        Pager<ZtcTransport> ztcTransports = ztcTransportDao.getAreaCompany(pageSize,pageNumber,search);
        List<HashMap<String, Object>> list = new ArrayList<>();
        HashMap<String, Object> map = null;
        if (ztcTransports.getContent().size() > 0) {
            for (ZtcTransport ztc : ztcTransports.getContent()) {
                map = new HashMap<>();
                map.put("name", ztc.getFullName());
                map.put("signTel", ztc.getSignTel());
                map.put("address", ztc.getAddress());
                map.put("status", ztc.getStatus());
                map.put("email", ztc.getEmail());
                map.put("location",sysAreaDao.findUniqueBy("code",ztc.getAreaCode()).getFullName());
                map.put("type", getCompanyType(ztc.getType()));
                map.put("time", DateFarmatUtils.format(ztc.getSignTime()));
                map.put("id", ztc.getId());
                map.put("levelType", ztc.getType());
                list.add(map);
            }
            return JsonWrapper.successPagerWrapper(list,ztcTransports.getRecordTotal());
        }
        return JsonWrapper.successWrapper("");
    }

    //冻结，解冻公司
    @Transactional
    public HashMap<String,Object> setTransportStatus(Integer status,ZtcTransport ztcTransport,User user){
        //冻结操作
        if(status==4){
            //冻结运营公司
            if(ztcTransport.getType()==3){
               log.info("===========》开始扫描运营“"+ztcTransport.getFullName()+"”旗下车方列表公司=====");
               List<ZtcTransport> ztcTransportList=ztcTransportDao.getChildZtcTransportList(ztcTransport.getId());
               if(ztcTransportList.size()>0){
                   for (ZtcTransport z : ztcTransportList) {
                       log.info("=============》开始执行冻结‘"+z.getFullName()+"’（"+z.getId()+"）车方的操作======");
                       //z公司设置冻结
                       z.setStatus(status);
                       ztcTransportDao.update(z);
                       stopRouteAndClassesInfo(z.getId(), user);
                   }
               }
                stopRouteAndClassesInfo(ztcTransport.getId(), user);
            }
            //冻结车方
            if(ztcTransport.getType()==4){
                stopRouteAndClassesInfo(ztcTransport.getId(), user);
            }
        }
        ztcTransport.setStatus(status);
        ztcTransportDao.update(ztcTransport);
        return JsonWrapper.successWrapper("操作成功！");
    }

    private void stopRouteAndClassesInfo(String id, User user) {
        //获取z公司所有线路
        List<ZtcRoute> ztcRouteList = ztcRouteDao.findBy("fkZtcTransportId",id);
        if (ztcRouteList.size() > 0) {
            for (ZtcRoute ztcRoute : ztcRouteList) {

                //z公司线路冻结
                ztcRoute.setStatus(3);
                ztcRoute.setUpdateUserName(user.getName() == null ? user.getAccount() : user.getName());
                ztcRoute.setUpdateTime(new Date());
                ztcRoute.setFkUpdateUserId(user.getId());
                ztcRouteDao.save(ztcRoute);

                //获取ztcRoute线路生产的所有班次信息
                List<ZtcClasses> ztcClassesList = ztcClassesDao.findBy("fkZtcRouteId", ztcRoute.getId());
                if (ztcClassesList.size() > 0) {
                    for (ZtcClasses ztcClasses : ztcClassesList) {

                        //z公司班次信息冻结
                        ztcClasses.setTicketStatus(1);
                        ztcClasses.setFkModifyUserId(user.getId());
                        ztcClasses.setModifyTime(new Date());
                        ztcClassesDao.save(ztcClasses);

                        //获取z公司所有在售班次
                        List<ZtcClassesForSale> ztcClassesForSaleList = ztcClassesForSaleDao.findBy("fkZtcClassesId", ztcClasses.getId());
                        if (ztcClassesForSaleList.size() > 0) {
                            for (ZtcClassesForSale ztcClassesForSale : ztcClassesForSaleList) {

                                //z公司在售班次冻结
                                ztcClassesForSale.setTicketStatus(1);
                                ztcClassesForSale.setFkModifyUserId(user.getId());
                                ztcClassesForSale.setModifyTime(new Date());
                                ztcClassesForSaleDao.save(ztcClassesForSale);
                            }
                        }
                    }
                }
            }
        }
    }

    // 被冻结车方，更换申请更换上级运营公司
    @Transactional
    public HashMap<String,Object> applyChangeHigher(ZtcTransport ztcTransport, String pid, String cid, String did) {
        ZtcCar ztcCar = ztcCarDao.get(cid);
        if(ztcCar==null){
            return JsonWrapper.failureWrapperMsg("车辆不存在！");
        }
        ZtcDriver ztcDriver = ztcDriverDao.get(did);
        if(ztcDriver==null){
            return JsonWrapper.failureWrapperMsg("司机不存在！");
        }
        ztcTransport.setParentId(pid);
        ztcTransport.setStatus(1);
        ztcTransportDao.save(ztcTransport);
        ztcCar.setStatus(5);
        ztcDriver.setStatus("5");
        ztcCarDao.save(ztcCar);
        ztcDriverDao.save(ztcDriver);
        return JsonWrapper.successWrapper("提交成功，请等待审核！");
    }

    //获取所有营业执照到期且未被冻结的运营公司
    public List<ZtcTransport> getExpireZtcTransport() {
      return ztcTransportDao.getExpireZtcTransport();
    }

    //获取快递公司列表根据状态(待审核，全部不含待审核)
    public HashMap<String,Object> getExpressListByType(Integer type,Integer pageSize,Integer pageNumber,String search){
       Pager<Map> pager= ztcTransportDao.getExpressListByType(type,pageSize,pageNumber,search);
       return JsonWrapper.successPagerWrapper(pager.getContent(),pager.getRecordTotal());
    }
}